package org.wheel.base.service.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.wheel.base.dao.IBaseDao;
import org.wheel.base.model.BaseModel;
import org.wheel.base.service.IBaseService;

/**
 * @author klaus.wang
 * eg: SysUserServiceImpl extends AbstractService<SysUserDao, SysUser> implements SysUserService {} 
 */
public abstract class AbstractService<D extends IBaseDao<T>, T> implements IBaseService<T> {

	protected D dao;

	@Override
	public void insert(T entity) {
		this.dao.insert(entity);
	}

	@Override
	public void insert_dynamic(T entity) {
		this.dao.insert_dynamic(entity);
	}

	@Override
	public void update(T entity) {
		this.dao.update(entity);
	}

	@Override
	public void update_dynamic(T entity) {
		this.dao.update_dynamic(entity);
	}

	@Override
	public void deleteById(Serializable id) {
		this.dao.deleteById(id);
	}

	@Override
	public T getById(Serializable id) {
		return this.dao.getById(id);
	}

	@Override
	public List<T> list(Object params) {
		return this.dao.list(params);
	}

	/**
	 * save or update ? 根据id判断或者根据主键对象
	 */
	@Override
	public void saveOrUpdate(T entity) {
		if (this.isInsert(entity)) {
			dao.insert_dynamic(entity);
		} else {
			dao.update_dynamic(entity);
		}
	}

	/**
	 * 根据id判断或者根据主键对象
	 * 
	 * @param entity
	 * @return
	 */
	protected boolean isInsert(T entity) {
		if (entity instanceof BaseModel) {

			String id = ((BaseModel) entity).getId();
			boolean idNotNull = StringUtils.isNotBlank(id);

			if (idNotNull) {
				// 判断数据库主键对象是否存在 TODO
				// idNotNull = idNotNull && dao.getById(id) != null;
			}

			return !idNotNull;
		}
		return true;
	}

	public D getDao() {
		return dao;
	}

	@Resource
	public void setDao(D dao) {
		this.dao = dao;
	}

}
